var time;
var init = 0; var init2 = 0;
var innerAudioContext;//背景音乐对象
var button;//按钮音乐对象
var time1;//定时器赋值
Page({

  /**
   * 页面的初始数据
   */
  data: {
    request_url: '',//url地址
    openid:"",
    difficulty:"",//方差 难度系数
    passScore:0,//过关分数
    exceedRate: 0,//超过用户数百分比
    ifHidden: true,//是否隐藏
    guideAnimation: {},//动画
    code: 0,//用户是否第一次进入
    aniDisplay: "none",//指导动画显示
    targetColor: '',
    adjustmentColor: 'rgb(255, 255, 255)',
    timeColor: 'blue',
    usefulIndex: [],//图片需要改的像素点下标
    ifFirstChange: true,
    //关卡
    maskIndex: 0,
    maskNum: 0,//关卡总数
    //屏幕相关信息
    windowWidth: '',
    windowHeight: '',
    windowscale: '',
    imageInfo: '',//图片信息
    imagewidth: '',//图片缩放后的宽  
    imageheight: '',//图片缩放后的高
    //目标色，当前色和倒计时
    sumIndex: 0,//目标色，当前色和倒计时canvasid
    targetColorIndex: 1,//目标色canvasid
    adjustmentColorIndex: 3,//当前色canvasid
    timeIndex: 5,//倒计时canvasid
    sliderIndex: 7,//滑动轴canvasid
    //颜色轴
    sliderLevels: '',
    targetRed: '',
    targetGreen: '',
    targetBlue: '',
    SliderValue1: '',
    SliderValue2: '',
    SliderValue3: '',
    sliderNumber: '',
    ifSliderDisabled1: '',
    ifSliderDisabled2: '',
    ifSliderDisabled3: '',
    redBar: '',
    greenBar: '',
    blueBar: '',
    redBc: '',//红色滑块颜色
    greenBc: '',//绿色滑块颜色
    blueBc: '',//蓝色滑块颜色
    redBarIcon:'',//红色小三角
    greenBarIcon: '',//绿色小三角
    blueBarIcon: '',//蓝色小三角
    activeGreen:'grey',//红色激活颜色
    activeGreen:'grey',//绿色激活颜色
    activeBlue:'grey',//蓝色激活颜色
    backgroundRed:"grey",//红色未激活颜色
    backgroundGreen:"grey",//绿色未激活颜色
    backgroundBlue:"grey",//蓝色未激活颜色
    second: 15,//倒计时
    sumTime: 0,//累计时间
    score: 0,//累积分数
    scoreCal: [],//分数计算系数
    sec: 15,//每次增加秒数
    sum: 100,//分数上限
    ori: 25,//分数下限
    mul:5,//倍乘系数
    scoreSum:0,//总分
    sliderChangingUseless: false,//sliderchanging是否有用
    sliderChange: true,//sliderChange是否有用
    //关卡
    beforeLevel: 8,//其他图层总数
    presentLevel: 8,//当前所处关卡
    array1: [],//循环渲染数组
    computerColorDifference: '',//目标色和当前色差值
    mainInterfaceSrc: '../../img/mainInterface/bg.jpg',//总体背景图
    hint_bgSrc: '../../img/mainInterface/hint_bg.png',//目标色，当前色背景图
    slider_bgSrc: '../../img/mainInterface/slider_bg.png',//滑块背景图
    targetColorSrc: '../../img/mainInterface/targetColor.png',//目标色
    currentColorSrc: '../../img/mainInterface/currentColor.png',//当前色
    noColorSrc: [],//无颜色的
    haveColorSrc: [],//有颜色的
    borderSrc: [],//边框
    FloorImage: '',//面具底图
    home_time_src: '../../img/mainInterface/',
    // home_time1_src: '../../img/mainInterface/15.png',
    // home_time2_src: '../../img/mainInterface/15.png',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let vm = this
    //获取接口地址、openid、难度系数
    var request_url = wx.getStorageSync('request_url')
    var openid = wx.getStorageSync('openid')
    var difficulty = wx.getStorageSync('difficulty')
    // var code = wx.getStorageSync('code')    
    
    vm.setData({
      maskIndex: options.maskIndex,//面具
      maskNum: options.maskNum,//关卡总数
      request_url: request_url,
      openid: openid,
      difficulty: difficulty,
      code: options.code,
      passScore: options.passScore
    })
    //加载
    vm.loading()
    //获取接口有颜色的图片信息
    vm.getHaveColorImage()
    //获得设备信息
    vm.getSystemInformation()
    vm.getSliderInfor()
    vm.getScoreInfor()
  },
  //加载
  loading: function () {
    wx.showLoading({
      title: '加载中',
    })
  },
  //停止加载
  endLoading: function () {
    this.setData({
      ifHidden: false
    })
    wx.hideLoading()
  },
  //获取关于slider的接口
  getSliderInfor: function () {
    let vm = this
    wx.request({
      url: vm.data.request_url + '/MianJuJiang/mask/getMaskSetting/'
      + vm.data.maskIndex,
      method: 'GET',
      success: function (res) {
        console.log("后台请求成功");
        console.log(res.data.levels);
        vm.setData({
          sliderLevels: res.data.levels
        })

      },
      fail: function (res) {
        console.log("后台请求失败");
      }
    })
  },
  //获取各个等级分数系数的接口
  getScoreInfor: function (level) {
    let vm = this
    var temp = []

    wx.request({
      url: vm.data.request_url + '/MianJuJiang/score/scoreMethod',
      method: 'GET',
      success: function (res) {
        console.log("后台请求成功");

        for (var key in res.data) {
          for (var i = 0; i < 3; i++) {
            temp.push(res.data[key][i])
          }
        }
        vm.setData({
          scoreCal: temp
        })
      },
      fail: function (res) {
        console.log("后台请求失败");
        console.log(res.data);
      }
    })
  },

  //计算和滑块相关的
  setSlider: function (level) {
    //level表示第几关
    let vm = this
    var i = parseInt(level)
    console.log(i)
    console.log(vm.data.sliderLevels[i].g)
    var slider = vm.data.sliderLevels[i].slider
    var r = vm.data.sliderLevels[i].r
    var g = vm.data.sliderLevels[i].g
    var b = vm.data.sliderLevels[i].b

    var targetColor = 'rgb(' + r + ',' + g + ',' + b + ')'
    vm.setData({
      targetColor: targetColor,//目标色，显示背景色
      targetRed: r,//目标红色轴的值，用于计算差值
      targetGreen: g,//目标绿色轴的值，用于计算差值
      targetBlue: b//目标蓝色轴的值，用于计算差值
    })
    console.log(slider)
    if (slider == 'r') {
      //红色轴
      vm.setData({
        sliderNumber: 1,
        ifSliderDisabled1: false,
        ifSliderDisabled2: true,//绿色轴不可用
        ifSliderDisabled3: true,
        redBar: 0,
        greenBar: g,//固定最后计算值
        blueBar: b,
        SliderValue2: g,//固定数值
        SliderValue3: b,
        redBc: "red",
        greenBc: "white",
        blueBc: "white",
        activeRed:"red",
        backgroundRed:"white",
        redBarIcon:"../../img/mainInterface/R.png"//设置红色小三角
      })
      if (level != 0) {
        vm.scoreCal(0)
      }

    } else if (slider == 'rg') {
      console.log('红色，绿色轴')
      //红色，绿色轴
      vm.setData({
        sliderNumber: 2,
        ifSliderDisabled1: false,
        ifSliderDisabled2: false,
        ifSliderDisabled3: true,
        redBar: 0,
        greenBar: 0,
        blueBar: b,
        redBc: "red",
        greenBc: "green",
        blueBc: "white",
        activeRed: "red",
        backgroundRed: "white",
        activeGreen: "green",
        backgroundGreen: "white",
        SliderValue3: b,
        redBarIcon: "../../img/mainInterface/R.png",//设置红色小三角
        greenBarIcon: "../../img/mainInterface/G.png"//设置绿色小三角
      })
      if (level != 0) {
        vm.scoreCal(1)
      }
    } else if (slider == 'rgb') {
      vm.setData({
        sliderNumber: 3,
        ifSliderDisabled1: false,
        ifSliderDisabled2: false,
        ifSliderDisabled3: false,
        redBc: "red",
        greenBc: "green",
        blueBc: "blue",
        redBar: 0,
        greenBar: 0,
        blueBar: 0,
        activeRed: "red",
        backgroundRed: "white",
        activeGreen: "green",
        backgroundGreen: "white",
        activeBlue: "Blue",
        backgroundBlue: "white",
        redBarIcon: "../../img/mainInterface/R.png",//设置红色小三角
        greenBarIcon: "../../img/mainInterface/G.png",//设置绿色小三角
        blueBarIcon: "../../img/mainInterface/B.png",//设置蓝色小三角
      })
      if (level != 0) {
        vm.scoreCal(2)
      }
    }
  },
  //计算时间加分
  setSliderNumber: function (level) {
    let vm = this
    var i = parseInt(level)
    var slider = vm.data.sliderLevels[i].slider
    if (slider == 'r') {
      var src = vm.data.home_time_src+this.data.sec+'.png'
    } else if (slider == 'rg') {
      var src = vm.data.home_time_src + this.data.sec + '.png'
    } else {
      var src = vm.data.home_time_src + this.data.sec + '.png'
    }
    return src
  },
  //获取底图
  getFloorImage: function () {
    console.log('获取图片信息')
    let vm = this
    wx.request({
      url: vm.data.request_url + '/MianJuJiang/img/getFloorImg/'
      + vm.data.maskIndex,
      method: 'GET',
      success: function (res) {
        console.log("后台请求成功");
        // console.log(res.data);
        var temp = vm.data.request_url + '/' + res.data.imgData
        // vm.setData({
        //   FloorImage: temp
        // })
        vm.downLoadFloor(temp)
      },
      fail: function (res) {
        console.log("后台请求失败");
        console.log(res.data);
      }
    })
  },
  //获取有颜色的图片信息
  getHaveColorImage: function () {
    console.log('获取图片信息')
    console.log(this.data.request_url)
    let vm = this
    //请求后台接口
    wx.request({
      url: vm.data.request_url + '/MianJuJiang/img/getSubImg/'
      + vm.data.maskIndex + '-1',
      method: 'GET',
      success: function (res) {
        console.log("后台请求成功");
        console.log(res.data);
        var jslength = 0;

        for (var key in res.data) {
          jslength++;
        }
        var temp = new Array(jslength)
        for (var key in res.data) {
          var file = vm.data.request_url + '/' + res.data[key]
          // temp.push({ src: vm.data.request_url + '/' + res.data[key] })
          vm.downLoadHaveColor(file, temp, parseInt(key) - 1)
        }
        //获取无颜色的图片信息
        vm.getNoColorImage()

      },
      fail: function (res) {
        console.log("后台请求失败");
        console.log(res.data);
      }
    })
  },
  //获取无颜色的图片信息
  getNoColorImage: function () {
    console.log('获取图片信息')
    let vm = this
    wx.request({
      url: vm.data.request_url + '/MianJuJiang/img/getSubImg/'
      + vm.data.maskIndex + '-2',
      method: 'GET',
      success: function (res) {
        console.log("后台请求成功");
        var jslength = 0;

        for (var key in res.data) {
          jslength++;
        }
        var temp = new Array(jslength)
        for (var key in res.data) {
          var file = vm.data.request_url + '/' + res.data[key]
          vm.downLoadNoColor(file, temp, parseInt(key) - 1)
        }
        vm.getFloorImage()
      },
      fail: function (res) {
        console.log("后台请求失败");
        console.log(res.data);
      }
    })
  },
  //下载有颜色的
  downLoadHaveColor: function (url, temp, index) {
    var temp = temp
    let vm = this
    //下载
    wx.downloadFile({
      url: url,
      success: function (res) {
        console.log(res)
        console.log(res.tempFilePath)
        //保存到本地
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success: function (res) {
            console.log(res.savedFilePath)
            console.log('成功')
            temp[index] = res.savedFilePath
            vm.setData({
              haveColorSrc: temp
            })
            console.log(vm.data.haveColorSrc)
            return temp
          }
        })
      }
    })
  },
  //下载无颜色的
  downLoadNoColor: function (url, temp, index) {
    var temp = temp
    let vm = this
    //下载
    wx.downloadFile({
      url: url,
      success: function (res) {
        console.log(res)
        console.log(res.tempFilePath)
        //保存到本地
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success: function (res) {
            console.log(res.savedFilePath)
            console.log('成功')
            temp[index] = res.savedFilePath
            vm.setData({
              noColorSrc: temp
            })
            console.log(vm.data.noColorSrc)
            return temp
          }
        })
      }
    })
  },
  //下载面具底图
  downLoadFloor: function (url, temp) {
    var temp = temp
    let vm = this
    wx.downloadFile({
      url: url,
      success: function (res) {
        console.log(res)
        console.log(res.tempFilePath)
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success: function (res) {
            console.log(res.savedFilePath)
            console.log('成功')
            vm.setData({
              FloorImage: res.savedFilePath
            })
            console.log(vm.data.FloorImage)
            //初始化
            vm.initInfo()
            countdown(vm, vm.data.second)
          }
        })
      }
    })

  },
  // 获取设备信息
  getSystemInformation() {
    // 获取设备信息。
    let vm = this
    wx.getSystemInfo({
      success: function (res) {
        vm.setData({
          windowWidth: res.screenWidth//可使用宽度
        })
        vm.setData({
          windowHeight: res.screenHeight//可使用高度
        })
        vm.setData({
          windowscale: res.screenHeight / res.screenWidth//可使用宽度
        })
      }
    })
  },
  //初次进入
  initInfo: function () {
    let vm = this
    //获得该关卡的图片资源
    //初始化循环渲染面具层数组，全部渲染出来
    var arrayTemp = []
    console.log(vm.data.maskNum)
    //面具每个关卡图层下标
    for (var i = 0; i < vm.data.maskNum; i++) {
      arrayTemp.push({ index: i + 8 })
      vm.setData({
        array1: arrayTemp
      })
    }
    console.log(vm.data.array1)
    //当前色设置
    vm.setData({
      adjustmentColor: 'rgb(255, 255, 255)'
    })
    //面具图层第一层渲染(人脸层)
    //获取图片信息并且渲染面具图层
    var level = 8
    vm.getImageInformation(vm.data.FloorImage, level)
  },
  //获取图片信息
  getImageInformation(src, i) {
    console.log('进入')
    var src = src
    var level = i//所要操作的图层
    // console.log(level)
    var imageSize = {
      imageWidth: '',
      imageHeight: '',
      originalScale: ''
    };
    let vm = this
    //获得图片信息
    wx.getImageInfo({
      src: src,
      success: function (res) {
        console.log(res)
        imageSize.imageWidth = res.width
        imageSize.imageHeight = res.height
        imageSize.originalScale = res.height / res.width
        //决定宽度和高度
        var imageInfoTemp = vm.setImageInformation(imageSize)
        vm.setData({
          imageInfo: imageInfoTemp//图片缩放后的信息
        })
        vm.setData({
          imagewidth: imageInfoTemp.imageWidth//图片缩放后的宽  
        })
        vm.setData({
          imageheight: imageInfoTemp.imageHeight//图片缩放后的高
        })
        //面具整体，底图出现
        console.log(vm.data.FloorImage)
        var cxt = wx.createCanvasContext('myCanvas6')
        cxt.drawImage(vm.data.FloorImage, 0, 0, vm.data.imagewidth, vm.data.imageheight)
        cxt.draw(true, function () {
        })
        //初始化第一个要操作的图层
        console.log('第 1 关')
        console.log('myCanvas' + level)
        var cxt2 = wx.createCanvasContext('myCanvas' + level)
        cxt2.drawImage(vm.data.noColorSrc[0], 0, 0, vm.data.imagewidth, vm.data.imageheight)
        cxt2.draw(true, function () {
          console.log('1111')
        })
        //设置第一层滑块显示数
        vm.setSlider(0)
        //加载结束
        vm.endLoading()
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  //设定图片宽度和高度
  setImageInformation(imageInfor) {
    var imageSize = {
      imageWidth: '',
      imageHeight: '',
      originalScale: ''
    }
    imageSize.imageHeight = this.data.windowHeight * 0.6
    imageSize.imageWidth = imageSize.imageHeight / imageInfor.originalScale
    console.log(imageSize)
    return imageSize
  },
  //面具层涂色
  changeImage: function () {
    let vm = this
    //更改的图层
    var level = vm.data.presentLevel
    //处在第几关
    var level2 = vm.data.presentLevel - 7
    //面具层更改
    var canvasId = 'myCanvas' + level
    // console.log(canvasId)
    // console.log('正要更改第' + level2 +'关')
    //获取图片像素信息
    wx.canvasGetImageData({
      canvasId: canvasId,
      x: 0,
      y: 0,
      width: vm.data.imagewidth,
      height: vm.data.imageheight,
      success(res) {
        var tempt = []
        // 修改颜色
        if (vm.data.ifFirstChange == true) {
          console.log('第一次')
          // var time1 = Date.now() 
          for (var i = 0; i < res.data.length; i += 4) {
            if (res.data[i + 3] != 0) {
              res.data[i] = vm.data.redBar
              res.data[i + 1] = vm.data.greenBar
              res.data[i + 2] = vm.data.blueBar
              tempt.push(i)
            }
          }
          // var time2 = Date.now()
          //放有用的像素点坐标 
          vm.setData({
            usefulIndex: tempt
          })
        } else {
          console.log('非第一次')
          // var time1 = Date.now()
          for (var j = 0; j < vm.data.usefulIndex.length; j++) {
            var i = vm.data.usefulIndex[j]
            res.data[i] = vm.data.redBar
            res.data[i + 1] = vm.data.greenBar
            res.data[i + 2] = vm.data.blueBar
          }
        }
        vm.setData({
          ifFirstChange: false
        })
        //获取上下文
        const ctx1 = wx.createCanvasContext(canvasId)
        //重新绘图
        wx.canvasPutImageData({
          canvasId: canvasId,
          x: 0,
          y: 0,
          width: vm.data.imagewidth,
          height: vm.data.imageheight,
          data: res.data,
          success(res) {
            console.log(res)
            //计算差值,计算是否进入下一关
            vm.computerColorDifference(level2)
          },
          fail(res) {
            console.log(res)
          }
        })
        ctx1.draw(true, function (e) {
          console.log('draw callback')
        })
      },
      fail(res) {
        console.log(res)
      }
    })
  },
  //滑块停止时
  slider1change: function (e) {
    if (this.data.sliderChange == true) {
      console.log(e.detail.value)
      this.setData({
        redBar: e.detail.value
      })
      //改变图层颜色
      this.changeImage()
    }
  },
  slider2change: function (e) {
    if (this.data.sliderChange == true) {
      console.log(e.detail.value)
      this.setData({
        greenBar: e.detail.value
      })
      //改变图层颜色
      this.changeImage()
    }

  },
  slider3change: function (e) {
    if (this.data.sliderChange == true) {
      console.log(e)
      this.data.blueBar = e.detail.value
      this.setData({
        blueBar: e.detail.value
      })
      //改变图层颜色
      this.changeImage()
    }

  },
  //滑块滑动时
  slider1changing: function (e) {
    let vm = this
    if (vm.data.sliderChangingUseless == false) {
      var color = "rgb(" + e.detail.value + "," + vm.data.greenBar + "," + vm.data.blueBar + ")";
      vm.setData({
        adjustmentColor: color,
        redBar: e.detail.value
      })

    }

  },
  slider2changing: function (e) {
    let vm = this
    if (vm.data.sliderChangingUseless == false) {
      var color = "rgb(" + vm.data.redBar + "," + e.detail.value + "," + vm.data.blueBar + ")";
      vm.setData({
        adjustmentColor: color,
        greenBar: e.detail.value
      })
    }

  },
  slider3changing: function (e) {
    let vm = this
    if (vm.data.sliderChangingUseless == false) {
      var color = "rgb(" + vm.data.redBar + "," + vm.data.greenBar + "," + e.detail.value + ")";
      vm.setData({
        adjustmentColor: color,
        blueBar: e.detail.value
      })
    }

  },
  //计算方差值
  computerColorDifference: function (level) {
    let vm = this
    //计算公式
    var computerColorDifferenceTempt = [(vm.data.blueBar - vm.data.targetBlue) * (vm.data.blueBar - vm.data.targetBlue) + (vm.data.greenBar - vm.data.targetGreen) * (vm.data.greenBar - vm.data.targetGreen) + (vm.data.redBar - vm.data.targetRed) * (vm.data.redBar - vm.data.targetRed)]
    //开平方
    var computerColorDifference = Math.sqrt(computerColorDifferenceTempt) / 255
    vm.setData({
      computerColorDifference: computerColorDifference
    })
    console.log(vm.data.computerColorDifference)
    if (vm.data.computerColorDifference < vm.data.difficulty) {
      var level2 = level + 7
      var i = level - 1
      //面具图层替换成最终
      var cxt = wx.createCanvasContext('myCanvas' + level2)
      cxt.drawImage(vm.data.haveColorSrc[i], 0, 0, vm.data.imagewidth, vm.data.imageheight)
      cxt.draw(false, function () {
        console.log('2222')
      })
      //清除定时器
      vm.setData({
        aniDisplay: "none"//不显示指导教程
      })
      clearInterval(time1)
      //替换下一关当前色为白色
      vm.nextColorChange()
      if (level < vm.data.maskNum) {
        // 如果成功，渲染下个图层
        console.log('进行下一关')
        this.button("matchsuccess", true, false);
        //计算下一关加时间数
        var i = vm.data.presentLevel - 7
        var src = vm.setSliderNumber(i)
        //加分层出现
        var cxt = wx.createCanvasContext('myCanvas2')
        cxt.drawImage(src, 0, 0, vm.data.imagewidth, vm.data.imageheight)
        cxt.draw(true, function () {
          console.log('33333')
        })
        //1秒后进入下一关
        setTimeout(function () {
          vm.nextLevel()
        }.bind(this), 1000)
        // vm.nextLevel()
      } else {
        console.log('全部通关')
        vm.data.sliderChangingUseless = true
        vm.data.sliderChange = false
          //页面跳转       
            wx.request({      //初始化用户信息
              url: vm.data.request_url + "/MianJuJiang/mask/updateScore/",
              method: "post",
              data: 'openId=' + vm.data.openid +
              '&maskId=' + vm.data.maskIndex +
              '&score=' + vm.data.scoreSum,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
              },
              success: function (response) {
                console.log(response);
                vm.setData({
                  sumTime:0,
                  exceedRate: response.data.exceedRate
                })
                console.log(vm.data.exceedRate);
                clearTimeout(time)
                //判断是否是否能戴上面具
                var hide;
                if (vm.data.scoreSum >= vm.data.passScore) {
                  hide = "../../img/result/wear.png"
                } else {
                  hide = "../../img/result/unwear.png"
                }
                wx.redirectTo({
                  url: '../../pages/end/end?maskIndex=' + vm.data.maskIndex
                  + '&scoreSum=' + vm.data.scoreSum
                  + '&exceedRate=' + vm.data.exceedRate
                  +'&hide='+hide,
                })
              }
            })
      }
    } else {
      console.log('没达到色彩要求')
    }

  },
  //进行下一关
  nextLevel: function () {

    //加分层消失
    var cxt = wx.createCanvasContext('myCanvas2')
    cxt.draw(false, function () {
      console.log('33333')
    })
    let vm = this
    //滑动轴归0
    vm.setData({
      SliderValue1: 0,
      SliderValue2: 0,
      SliderValue3: 0
    })
    vm.data.presentLevel = vm.data.presentLevel + 1//下一关
    // console.log(vm.data.presentLevel)
    vm.setData({
      ifFirstChange: true,
      usefulIndex: []
    })
    // 面具图层渲染
    // 获取要画的面具图层图片信息并且初始化图层
    var level = vm.data.presentLevel
    var i = vm.data.presentLevel - 8 //因为图片下标从0开始
    //设置滑块显示数
    vm.setSlider(i)
    //倒计时
    clearTimeout(time)
    countdown(vm, this.data.sumTime)
    //替换下一关图层
    vm.nextLevelGetImageInformation(vm.data.noColorSrc[i], level)

  },
  //下一关图层
  nextLevelGetImageInformation: function (src, i) {
    var level = i//所处关卡，所要操作的图层
    console.log(level)
    let vm = this
    //初始化图层
    console.log('myCanvas' + level)
    console.log(src)
    //面具图层
    var cxt = wx.createCanvasContext('myCanvas' + level)
    cxt.drawImage(src, 0, 0, vm.data.imagewidth, vm.data.imageheight)
    cxt.draw(true, function () {
      console.log('2222')
    })
  },
  //替换当前色为白色
  nextColorChange: function () {
    let vm = this
    console.log('change')
    //目标色，当前色设置
    vm.setData({
      adjustmentColor: 'rgb(255, 255, 255)'//白色
    })
  },
  //计算分数
  scoreCal(level) {
    let vm = this
    vm.setData({
      sumTime: this.data.second + this.data.sec
    })
    if ((this.data.ori + this.data.mul * this.data.second) > this.data.sum) {
      vm.setData({
        score: this.data.sum
      })
    } else {
      vm.setData({
        score: this.data.ori + this.data.mul * this.data.second
      })
    }
    vm.setData({
      sec: this.data.scoreCal[level].reward_time, //每次增加秒数
      sum: this.data.scoreCal[level].max_score,//分数上限
      ori: this.data.scoreCal[level].basic_score, //分数下限
      mul: this.data.scoreCal[level].mul_score, //乘秒倍数
      scoreSum: this.data.scoreSum+this.data.score//总分
    })

  },
  stopbgAudio: function () {
    innerAudioContext.stop();
  },
  button: function (u, a, l) {
    if (init2 == 0) {
      init2++;
      button = wx.createInnerAudioContext()
      button.autoplay = a;
      var urlKey = u;
      var savedFilePath = wx.getStorageSync(urlKey);
      button.src = savedFilePath;
      button.loop = l;
    } else {
      button.autoplay = a;
      button.src = wx.getStorageSync(u);
      button.loop = l;
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let vm=this
    wx.getSavedFileList({
      success: function (res) {
        var count = res.fileList.length
        var index = 0
        for (var i = 0; i < count; i++) {
          wx.removeSavedFile({
            filePath: res.fileList[index++].filePath,
            complete: function (res) {
              console.log(res)
            }
          })
        }
      }
    })
    clearTimeout(time)
    clearInterval(time1)
  },

  //指导动画
  onShow: function () {
    let vm = this
    //绑定动画
    var ii = 0
    if (vm.data.code == 0) {
      //绘制指引手势到画板
      // var cxt = wx.createCanvasContext('guideCanvus')
      // cxt.drawImage('../../img/start/guide.png', 0, 0, vm.data.windowHeight / 8, vm.data.windowHeight / 8)
      // cxt.draw(false, function () {
      //   console.log('guide')
      // })
      vm.setData({
        aniDisplay: "block"//显示指导教程
      })
      var guideAnimation = wx.createAnimation({
        duration: 100, // 默认为400     动画持续时间，单位ms
        timingFunction: 'ease-in-out',
        delay: 100,
      });
      time1 = setInterval(function () {
        //动画的脚本定义必须每次都重新生成，不能放在循环外
        guideAnimation.translate(145).step({ duration: 1000 }).translate().step({ duration: 1000 });
        // 更新数据
        vm.setData({
          // 导出动画示例
          guideAnimation: guideAnimation.export(),
        })
        ++ii;
        console.log(ii);
      }.bind(vm), 2000);
    }
  },
  change:function(){
    wx.redirectTo({
      url: '../../pages/level/level',
    })
  }
})

function countdown(that, s) {
  var second = s
  if (second == 0) {
    console.log("Time Out...");
    that.setData({
      second: 0
    });
    //判断是否是否能戴上面具
    var hide;
    if (that.data.scoreSum >= that.data.passScore){
      hide ="../../img/result/wear.png"
    }else{
      hide ="../../img/result/unwear.png"      
    }
    wx.request({      //初始化用户信息
      url: that.data.request_url + "/MianJuJiang/mask/updateScore/",
      method: "post",
      data: 'openId=' + that.data.openid +
      '&maskId=' + that.data.maskIndex+
      '&score=' + that.data.scoreSum,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      success: function (response) {
        console.log(response);
        that.setData({
          exceedRate: response.data.exceedRate
        })
        console.log(that.data.exceedRate);
        clearTimeout(time)
        wx.redirectTo({
          url: '../../pages/end/end?maskIndex=' + that.data.maskIndex
          + '&scoreSum=' + that.data.scoreSum
          + '&exceedRate=' + that.data.exceedRate
          +'&hide='+hide,
        })
      }
    })
    return;
  }

  time = setTimeout(function () {
    if (second == 10) {
      that.button("countdown", true, false);
    }
    that.setData({
      second: second
    });
    countdown(that, second - 1);
  }
    , 1000);
}